//
//  ReportViewController.m
//  安好
//
//  Created by lianchuang on 14/11/29.
//  Copyright (c) 2014年 lianchuangbrother. All rights reserved.
//

#import "ReportViewController.h"
#import "ReportCell.h"
#import "ReportMessageCell.h"
#import "ConsultingChatViewController.h"
#import "SquarePostsDetailsViewController.h"


#define RGB(r, g, b)    [UIColor colorWithRed:(r)/255.f green:(g)/255.f blue:(b)/255.f alpha:1.f]

@interface ReportViewController ()<UITableViewDataSource,UITableViewDelegate>
@property (nonatomic, strong) ReportCell *attributeCell;
@property (nonatomic, strong) NSString *reportContentType;
@property (nonatomic, strong) NSMutableDictionary *updataDic;
@property (nonatomic, strong) ReportMessageCell *chatRecordCell;
@end

@implementation ReportViewController
{
    NSArray *titleArray;
    NSArray *subTitleArray;
    BOOL cellSelect;
}

- (NSMutableDictionary *)updataDic{
    if (_updataDic == nil) {
        self.updataDic = [NSMutableDictionary dictionary];
    }
    return _updataDic;
}

- (ReportCell *)attributeCell{
    if (_attributeCell == nil) {
        _attributeCell = [[ReportCell alloc] init];
    }
    return _attributeCell;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    titleArray=@[@"色情",@"反动",@"欺诈",@"骚扰"];
    subTitleArray=@[@"（人体裸露图片、言语包含性描述等）",@"（涉嫌反党、反人民、扰乱社会治安等）",@"（骗钱、非法集资、引诱他人投资等）",@"（推销、传销、都收商品等行为）"];
    self.tableview.dataSource=self;
    self.tableview.delegate=self;
    self.tableview.separatorStyle=UITableViewCellSeparatorStyleNone;
    self.tableview.backgroundColor=[ClassMethodsViewController colorWithHexString:BACK_BACKGROUNDCOLOR_16];
//    self.tableview.frame=CGRectMake(0, 0, kScreenWidth, kScreenHeight-64);
    [self setNaviBarAttribute];
    
    cellSelect = NO;
    [[NSNotificationCenter defaultCenter] addObserverForName:@"SETREPORTSTRING" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note) {
        _reportMessage = [note.userInfo objectForKey:@"reportMessage"];
        self.messageCountString = [note.userInfo objectForKey:@"messageCount"];
//        [self.tableview reloadData];
        if ([self.messageCountString length] > 0 && ![self.messageCountString isEqualToString:@"0"]) {
            self.chatRecordCell.messageCountLabel.text = [NSString stringWithFormat:@"%@条消息", self.messageCountString];
        } else {
            self.chatRecordCell.messageCountLabel.text = [NSString stringWithFormat:@"无"];
        }
    }];
    // Do any additional setup after loading the view from its nib.
}

#pragma  mark UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if([[self.navigationController.viewControllers objectAtIndex:self.navigationController.viewControllers.count - 2] isKindOfClass:[ SquarePostsDetailsViewController class]]){
        return 1;
    }else if (self.isFromDocDetail){
        return 1;
    }
    else return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if ([[self.navigationController.viewControllers objectAtIndex:self.navigationController.viewControllers.count - 2] isKindOfClass:[ SquarePostsDetailsViewController class]]) {
        return 4;
    }
    else
    {
        if (section==0) {
            return 4;
        }else return 1;
    }
    
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==0) {
        static NSString *indentifier=@"cell";
        ReportCell *cell=[tableView dequeueReusableCellWithIdentifier:indentifier];
        if (cell==nil) {
            if (kScreenWidth == 414) {
                cell=[[[NSBundle mainBundle]loadNibNamed:@"ReportCell" owner:self options:nil] lastObject];
            }else{
                cell=[[[NSBundle mainBundle]loadNibNamed:@"ReportCell" owner:self options:nil] firstObject];
            }
        }
        cell.titleName.text=[titleArray objectAtIndex:indexPath.row];
        cell.subTitleName.text=[subTitleArray objectAtIndex:indexPath.row];
        if (cellSelect) {
            cell.reportImage.image=[UIImage imageNamed:@"report_select"];
        }else
        {
            cell.reportImage.image=[UIImage imageNamed:@"report_unselect"];
        }
        
        if (indexPath.row == 3) {
            cell.lineView.hidden = YES;
        }else{
            cell.longLineView.hidden = YES;
        }
        cell.lineView.backgroundColor = RGB(221, 221, 221);
        cell.longLineView.backgroundColor = RGB(221, 221, 221);
        
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        return cell;
    }else
    {
        static NSString *inden=@"setCell";
        ReportMessageCell *setCell=[tableView dequeueReusableCellWithIdentifier:inden];
        if (setCell==nil) {
            if (kScreenWidth == 414) {
                setCell=[[[NSBundle mainBundle]loadNibNamed:@"ReportMessageCell" owner:self options:nil] lastObject];
            }else{
                setCell=[[[NSBundle mainBundle]loadNibNamed:@"ReportMessageCell" owner:self options:nil] firstObject];
            }
        }
        
        setCell.firstLineView.backgroundColor = RGB(221, 221, 221);
        setCell.secondLineView.backgroundColor = RGB(221, 221, 221);
        if ([self.messageCountString length] > 0 && ![self.messageCountString isEqualToString:@"0"]) {
            setCell.messageCountLabel.text = [NSString stringWithFormat:@"%@条消息", self.messageCountString];
        } else {
            setCell.messageCountLabel.text = [NSString stringWithFormat:@"无"];
        }
        self.chatRecordCell = setCell;
        return setCell;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section==0) {
        return 0;
    }
    if (section == 1) {
//        if ([self.report_type intValue] == 3) {
        if ([self numberOfSectionsInTableView:self.tableview] == 2) {
            return 10;
        }else{
            return 0;
        }
    }
    return 0;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section==1) {
        UIView *view=[[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 10)];
        view.backgroundColor = [UIColor groupTableViewBackgroundColor];
        return view;
    }
    else{
        return nil;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (kScreenWidth == 414) {
        return 67;
    }else{
        return 56;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        
        ReportCell *cell=(ReportCell *)[tableView cellForRowAtIndexPath:indexPath];
        
        NSUInteger row = [indexPath row];
        
        
        if ([self.attributeCell isEqual:cell]) {
            if (!cellSelect) {
                cellSelect = YES;
                cell.reportImage.image = [UIImage imageNamed:@"report_select"];
                self.reportContentType = [NSString stringWithFormat:@"%lu",row + 1];
            }else
            {
                cell.reportImage.image = [UIImage imageNamed:@"report_unselect"];
                cellSelect = NO;
                self.reportContentType = [NSString stringWithFormat:@"100"];
            }
        }else{
            if (!cellSelect) {
                cellSelect = YES;
                self.attributeCell.reportImage.image = [UIImage imageNamed:@"report_unselect"];
                cell.reportImage.image = [UIImage imageNamed:@"report_select"];
                self.reportContentType = [NSString stringWithFormat:@"%lu",row + 1];
            }else{
                cell.reportImage.image = [UIImage imageNamed:@"report_select"];
                self.attributeCell.reportImage.image = [UIImage imageNamed:@"report_unselect"];
                self.reportContentType = [NSString stringWithFormat:@"%lu",row + 1];
            }
        }
        
        self.attributeCell = cell;
    }else
    {
        ConsultingChatViewController *chatView = [[ConsultingChatViewController alloc] init];
        if (self.reportType == 0) {
            chatView.qid = self.qid;
            chatView.touid = self.objectids;
            chatView.doctoruid=self.objectids;
            chatView.isFromwhere = 1;

        }else if(self.reportType == 1)
        {
            chatView.touid = self.objectids;
            chatView.isFromwhere = 0;
        }
        chatView.isFromReport = YES;
//        chatView.titeleString = self.username;
        chatView.userName=self.username;
        [self.navigationController pushViewController:chatView animated:YES];
    }
    
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - 设置naviBar 并实现左右naviBar button方法 -
- (void)setNaviBarAttribute{
    /**
     *  设置左NaviBar和右naviBar
     */
    UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    leftButton.frame = CGRectMake(0, 0, 23, 23);
    [leftButton setImage:[UIImage imageNamed:@"公用_返回"] forState:UIControlStateNormal];
    [leftButton addTarget:self action:@selector(handleLeftButtonAction) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    self.navigationItem.leftBarButtonItem = leftBarButtonItem;
    self.navigationItem.title = @"投诉";
    
    UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    rightButton.frame = CGRectMake(0, 0, 30, 23);
    [rightButton setTitle:@"发送" forState:UIControlStateNormal];
    rightButton.titleLabel.font = [UIFont systemFontOfSize:15];
    [rightButton addTarget:self action:@selector(handleRightButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
}

/**
 *  返回主页面
 */
- (void)handleLeftButtonAction{
    [self.navigationController popViewControllerAnimated:YES];
}

/**
 *  提交数据
 */
- (void)handleRightButtonAction:(UIButton *)sender{
    [self updateReportInfo];
}

#pragma mark - 上传投诉信息 -
- (void)updateReportInfo{
    [self showActionView];
    //postUrl
    NSString *postURL = [NSString stringWithFormat:@"%@common/report/",kBaseURL];
    //post参数列表
    [self.updataDic setValue:kPlatform forKey:@"platform"];
    [self.updataDic setValue:kVersion forKey:@"version"];
    [self.updataDic setValue:self.objectids forKey:@"objectids"];
    if ([self.reportContentType intValue] == 100) {
    }else{
        [self.updataDic setValue:self.reportContentType forKey:@"type"];
    }
    [self.updataDic setValue:self.report_type forKey:@"report_type"];
    if ([self.report_type intValue] == 3) {
        [self.updataDic setValue:_reportMessage forKey:@"description"];
    }
    //网络请求管理者
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    //开始请求
    [manager POST:postURL parameters:self.updataDic success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         NSNumber * statusNum = [responseObject objectForKey:@"status"];
         //用NSNumberFormatter把 NSNumber类型的数字-->转成字符串
         NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
         NSString * statusString = [numberFormatter stringFromNumber:statusNum];//得到字符串对象: "0" / "1"
         [self hiddenActionView];
         if ([statusString isEqualToString:@"0"])
         {
             [self showCustomHudSingleLine:@"提交失败"];
         }else
         {
             MyNSLog("提交成功");
             //  从数据库删除数据
//             [[NSNotificationCenter defaultCenter]removeObserver:self];
//             [self performSelector:@selector(popVC) withObject:nil afterDelay:1];
             
             [self.navigationController popViewControllerAnimated:YES];
         }
     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
     }];
}


//- (void)popVC{
//    [self.navigationController popViewControllerAnimated:YES];
//}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
